package com.example.project_springboot.service.impl;

import com.example.project_springboot.aop.MyLog;
import com.example.project_springboot.mapper.AccountMapper;
import com.example.project_springboot.pojo.Account;
import com.example.project_springboot.pojo.DeptLog;
import com.example.project_springboot.service.AccountService;
import com.example.project_springboot.service.DeptLogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
@Transactional
public class AccountServiceImpl implements AccountService {
    @Resource
    AccountMapper accountMapper;
    @Resource
    DeptLogService deptLogService;
    @MyLog
    public void transfer(String fromName, String toName, double amount) {
        boolean flag = true;
        Account fromAccount = accountMapper.findByName(fromName);
        Account toAccount = accountMapper.findByName1(toName);
        try {
            fromAccount.setMoney(fromAccount.getMoney() - amount);
            accountMapper.updateMoneyByName(fromName, fromAccount.getMoney());
            toAccount.setMoney(toAccount.getMoney() + amount);
            accountMapper.updateMoneyByName(toName, toAccount.getMoney());
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = false;
        } finally {
            DeptLog log = new DeptLog();
            log.setCreateTime(LocalDateTime.now());
            if (flag) {
                log.setDescription(fromName + "给" + toName + "转账，金额为" + fromAccount.getMoney() + "操作成功");
            } else {
                log.setDescription(fromName + "给" + toName + "转账，金额为" + fromAccount.getMoney() + "操作失败");
            }
            deptLogService.insert(log);
        }
    }
}